<?php

namespace tmcore\services\crud\generators;

use think\facade\Db;
use tmcore\services\crud\enum\CrudEnum;
use tmcore\services\crud\enum\TplEnum;
use tmcore\services\crud\UtilService;

class Sql extends Generate
{
    /**
     * @var string
     */
    protected string $fileType = 'sql';

    /**
     * 替换变量
     */
    public function replaceContent()
    {
        $search = [
            '{MENU_TABLE}',
            '{PARTNER_ID}',
            '{LISTS_NAME}',
            '{EDIT_PAGE_NAME}',
            '{DETAIL_PAGE_NAME}',
            '{PERMS_NAME}',
            '{PATHS_NAME}',
            '{COMPONENT_NAME}',
            '{CREATE_TIME}',
            '{UPDATE_TIME}',
            '{SQL_CONTENT}'
        ];

        $replace = [
            $this->getMenuTableNameContent(),
            $this->menuConfig['pid'],
            $this->menuConfig['name'],
            $this->getEditPageName(),
            $this->crudData['table_comment'] . '详情',
            $this->getPermsNameContent(),
            ($this->classDir ? $this->classDir . '/' : '') . UtilService::lcfirst($this->getCamelClassName()),
            ($this->classDir ? $this->classDir . '/' : '') . UtilService::lcfirst($this->getCamelClassName()),
            $this->params['time'],
            $this->params['time'],
            $this->getSqlContent()
        ];

        $content = UtilService::replaceFileContent($search, $replace, $this->getStub('sql'));

        $this->setContent($content);
    }

    /**
     * 返回模板路径
     * @param string $type
     * @return mixed|string|string[]
     */
    public function getStub(string $type = 'sql')
    {
        $basePath = 'sql/';

        $stubs = [
            'add' => $this->getTplPath($basePath . 'add'),
            'edit' => $this->getTplPath($basePath . 'edit'),
            'delete' => $this->getTplPath($basePath . 'delete'),
            'detail' => $this->getTplPath($basePath . 'detail'),
            'export' => $this->getTplPath($basePath . 'export'),
            'import' => $this->getTplPath($basePath . 'import'),
            'editPage' => $this->getTplPath($basePath . 'editPage'),
            'detailPage' => $this->getTplPath($basePath . 'detailPage'),
            'sql' => $this->getTplPath($basePath . 'sql'),
        ];

        return $type ? $stubs[$type] : $stubs;
    }

    /**
     * 设置文件路径
     */
    public function setFilePath()
    {
        $name =  'menu.' . $this->fileType;
        $this->setCrudFileName($name);

        $module_path = $this->crudDir . 'sql/';
        $this->setCrudModuleFilePath($module_path);

        $data_path = $this->crudDir . 'sql/';
        $this->setCrudDataFilePath($data_path);
    }

    /**
     * 获取编辑页面名称
     * @return string
     */
    public function getEditPageName()
    {
        if($this->crudData['is_insert'] && !$this->crudData['is_update'])  {
            $name = '添加';
        } else if($this->crudData['is_update'] && !$this->crudData['is_insert']) {
            $name = '编辑';
        } else {
            $name = '添加/编辑';
        }
        return $this->crudData['table_comment'] . $name;
    }

    /**
     * 获取sql内容
     * @return string|string[]
     */
    public function getSqlContent() {

        $search = [
            '{MENU_TABLE}',
            '{PARTNER_ID}',
            '{LISTS_NAME}',
            '{EDIT_PAGE_NAME}',
            '{DETAIL_PAGE_NAME}',
            '{PERMS_NAME}',
            '{PATHS_NAME}',
            '{COMPONENT_NAME}',
            '{CREATE_TIME}',
            '{UPDATE_TIME}',
        ];

        $replace = [
            $this->getMenuTableNameContent(),
            $this->menuConfig['pid'],
            $this->menuConfig['name'],
            $this->getEditPageName(),
            $this->crudData['table_comment'] . '详情',
            $this->getPermsNameContent(),
            ($this->classDir ? $this->classDir . '/' : '') . UtilService::lcfirst($this->getCamelClassName()),
            ($this->classDir ? $this->classDir . '/' : '') . UtilService::lcfirst($this->getCamelClassName()),
            $this->params['time'],
            $this->params['time'],
        ];

        return UtilService::replaceFileContent($search, $replace, $this->getStubContent(TplEnum::getSqlTpl($this->crudData)), false);
    }


    /**
     * 路由权限内容
     * @return string
     */
    public function getPermsNameContent()
    {
        return UtilService::lower($this->classDir) . ($this->classDir ? '/' : '') . UtilService::lcfirst($this->crudData['class_name']);
    }

    /**
     * 获取菜单表内容
     * @return string
     */
    public function getMenuTableNameContent()
    {
        $tablePrefix = config('database.connections.mysql.prefix');
        return $tablePrefix . 'system_menu';
    }

    /**
     * 是否构建自动菜单
     * @return bool
     */
    public function isBuildMenu()
    {
        return $this->menuConfig['type'] == CrudEnum::MENU_AT;
    }

    /**
     * 构建菜单
     * @return bool
     */
    public function buildMenuSql()
    {
        if (empty($this->content)) {
            return false;
        }
        $sqls = explode(';', trim($this->content));
        //执行sql
        foreach ($sqls as $sql) {
            if (!empty(trim($sql))) {
                Db::execute($sql . ';');
            }
        }
        return true;
    }
}